package com.itbaizhan;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*测试自启动servlet*/
/*自启动Servlet特点
自动启动Servlet表示在Tomcat启动时就会实例化这个Servlet，
他的实例化过程不依赖于请求，而是依赖容器的启动。

可以通过在web.xml中的标签中通过1配置自启动Servlet。
<load-on-startup>1</load-on-startup> 当有多个时，里面的整数越小，自启动越早
<servlet>
<servlet-name>autoStartServlet</servlet-name>
<servlet-class>com.itbaizhan.AutoStartServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>*/
public class AutoStartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在浏览器设置中文响应编码
        resp.setContentType("text/plain;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.println("AutoStartServlet。。。。!");
        pw.println("自启动Servlet");
    }
    //servlet实例化以后，会调用一次init()
    //重写无参的init()
    @Override
    public void init() throws ServletException {
        //获得ServletConfig对象
        ServletConfig servletConfig = this.getServletConfig();
        //获取servlet标签中的配置信息
        String value = servletConfig.getInitParameter("path");

        //获取全局容器对象
        ServletContext servletContext =this.getServletContext();
        //设置全局性数据
        servletContext.setAttribute("path",value);

    }
}
